var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors=require('cors');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var expressJWT = require('express-jwt')
var app = express();
app.use(cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use("/upload",express.static(path.join(__dirname, 'upload')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
// app.use(expressJWT({
//   secret:"123456",
//   algorithms:["HS256"],
//   //getToken是修改express-jwt获取请求头并判断的标准。默认是只有一个authorization，也就是我们请求头的Authorization字段，但是，如果我们想要他有多个判断时，比如，我们再要他判断一个pass，就可以像如下这么写
//   getToken: function fromHeaderOrQuerystring (req) {
  
//     if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
//       return req.headers.authorization.split(' ')[1];
//     }
//     if (req.headers.pass && req.headers.pass.split(' ')[0] === 'Bearer') {
//       return req.headers.pass.split(' ')[1];
//     }
//     return null;
//   }
// }).unless({path:["/login","/register"]}))
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
